package org.opencv.utils;


import android.graphics.Bitmap;
import android.util.Log;

import org.opencv.android.Utils;
import org.opencv.core.CvType;
import org.opencv.core.Mat;
import org.opencv.imgproc.Imgproc;

public class OpenCVUtils {
    public OpenCVUtils() {
    }

    //            boolean blurByOpenCV = OpenCVUtils.isBlurByOpenCV(ImageUtils.bytes2Bitmap(imageData));
//            ToastUtils.showLong(blurByOpenCV ? "图片模糊" : "图片清晰");

    public static boolean isBlurByOpenCV(Bitmap image) {
        Mat grayMatImage = bitmap2grayMatImage(image);
        Mat laplacianImage = new Mat();
        Imgproc.Laplacian(grayMatImage, laplacianImage, CvType.CV_8U); // 拉普拉斯变换

        Mat laplacMatResult = new Mat();
        laplacianImage.convertTo(laplacMatResult, CvType.CV_8UC1);

        Bitmap bmp = Bitmap.createBitmap(laplacMatResult.cols(), laplacMatResult.rows(), Bitmap.Config.ARGB_8888);
        Utils.matToBitmap(laplacMatResult, bmp);
        int[] pixels = new int[bmp.getHeight() * bmp.getWidth()];
        bmp.getPixels(pixels, 0, bmp.getWidth(), 0, 0, bmp.getWidth(), bmp.getHeight()); // bmp为轮廓图

        int maxLap = -16 * 1024 * 1024;
        for (int pixel : pixels) {
            if (pixel > maxLap)
                maxLap = pixel;
        }
        int soglia = -6118750; // -6118750为广泛使用的经验值
        Log.w("info", "maxLap :" + maxLap + " soglia: " + soglia);
        return maxLap <= soglia;
    }

    public static Mat bitmap2grayMatImage(Bitmap originImg) {
        Mat matImage = bitmap2mateImage(originImg);
        Mat matImageGrey = new Mat();
        Imgproc.cvtColor(matImage, matImageGrey, Imgproc.COLOR_BGR2GRAY); // 图像灰度化
        return matImageGrey;
    }


    public static Mat bitmap2mateImage(Bitmap originImg) {
        Bitmap destImage = Bitmap.createBitmap(originImg);
        Mat matImage = new Mat();
        Utils.bitmapToMat(destImage, matImage);
        return matImage;
    }

    static {
        System.loadLibrary("opencv_java3");
    }
}
